package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.ydd.common.R;
import com.itheima.ydd.entity.SysConfig;
import com.itheima.ydd.entity.SysUser;
import com.itheima.ydd.service.ISysConfigService;
import com.itheima.ydd.service.ISysUserService;
import com.itheima.ydd.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/index")
@Slf4j
@CrossOrigin
public class IndexController {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysConfigService sysConfigService;

    @PostMapping("/login")
    public R login(@RequestBody SysUser sysUser){
        log.info("登陆用户：{}",sysUser.toString());

        String loginName = sysUser.getLoginName();
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getLoginName, loginName);
        SysUser one = sysUserService.getOne(wrapper);

        if (one == null){
            return R.error("账号不存在");
        }else if (one.getStatus() == 0){
            return R.error("账号已禁用");
        }

        String password = sysUser.getPassword();
        if (one.getPassword().equals(generatePassword(password))){
            //把用户id 加密进token里

            // 生成token信息
            Map retMap = new HashMap();
            Map tokenMap = new HashMap<>();
            String roleId = one.getRoleId()
                    .replace("[","")
                    .replace("]", "")
                    .replace("\"", "");

            tokenMap.put("userId", one.getId());
            tokenMap.put("roleId", roleId);

            String token = JwtUtils.getToken(tokenMap);
            retMap.put("token", token);
            return R.success("token", JwtUtils.getToken(tokenMap));
        }
        return R.error("密码错误");

    }



    @GetMapping("/getConfig")
    public R systemConfig(){
        LambdaQueryWrapper<SysConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysConfig::getTabValue,"system");
        List<SysConfig> sysConfigs = sysConfigService.list(wrapper);

        HashMap<String, String> map = new HashMap<>();
        for (SysConfig sysConfig : sysConfigs) {
            map.put(sysConfig.getAttrKey(),sysConfig.getAttrValue());
        }

        return new R(map,"",0);

    }

    @PostMapping("/profile")
    public R profile(HttpServletRequest request){
        String token = request.getHeader("x-token");

        Claims claims = JwtUtils.getClaims(token);
        Long userId = Long.valueOf((String) claims.get("userId"));

        log.info("用户id:{}",userId);
        return sysUserService.profile(userId);
    }

    /** md5加密
     * @param password 密码
     */
    private String generatePassword(String password){
        return DigestUtils.md5DigestAsHex(password.getBytes());
    }

    @GetMapping("/baseInfo")
    public R baseInfo(){
        return sysUserService.baseInfo();
    }
}
